from sqlalchemy.orm import Session
from app.models.wallet import Wallet
from app.schemas.wallet import WalletCreate, WalletUpdate
from typing import List, Optional

def create_wallet(db: Session, wallet: WalletCreate, user_id: int) -> Wallet:
    db_wallet = Wallet(
        **wallet.model_dump(),
        user_id=user_id
    )
    db.add(db_wallet)
    try:
        db.commit()
        db.refresh(db_wallet)
        return db_wallet
    except Exception as e:
        db.rollback()
        raise e

def get_wallet(db: Session, wallet_id: int) -> Optional[Wallet]:
    return db.query(Wallet).filter(Wallet.id == wallet_id).first()

def get_user_wallets(db: Session, user_id: int) -> List[Wallet]:
    return db.query(Wallet).filter(Wallet.user_id == user_id).all()

def update_wallet(db: Session, wallet_id: int, wallet: WalletUpdate) -> Optional[Wallet]:
    db_wallet = get_wallet(db, wallet_id)
    if not db_wallet:
        return None
    
    for field, value in wallet.model_dump(exclude_unset=True).items():
        setattr(db_wallet, field, value)
    
    try:
        db.commit()
        db.refresh(db_wallet)
        return db_wallet
    except Exception as e:
        db.rollback()
        raise e

def delete_wallet(db: Session, wallet_id: int) -> bool:
    db_wallet = get_wallet(db, wallet_id)
    if not db_wallet:
        return False
    
    try:
        db.delete(db_wallet)
        db.commit()
        return True
    except Exception as e:
        db.rollback()
        raise e 